import React, { ReactNode, useRef, useState } from 'react';
import { Button, Col, Row, Image, Modal, Space, Tooltip, ConfigProvider } from 'antd/lib';
import { ActionType, ProColumns, ProFormInstance, ProTable } from '@ant-design/pro-components';
import { useNavigate } from 'react-router-dom-v5-compat';
import { fetchSubTaskList, fetchSubTaskStatusTypes } from 'apis/task';
import { auditTask, createTask, fetchLastReviewValid } from 'apis/annotation/task';
import { JobStatusEnum } from 'typings/annotion/task';
import { message } from 'antd';
import RejectForm from 'components/annotation-page/top-bar/reject-form';
import AuthPerm from 'components/common/AuthPerm';
import { AnnotationInfoIcon } from 'icons';

enum TaskItemReviewStateEnum {
    Tagging = 1, // 待标注
    FirstReview = 2, // 待初审
    FirstReviewReject = 3, // 初审驳回
    LastReview = 4, // 待复审
    LastReviewReject = 5, // 复审驳回
    PassLastReview = 6, // 复审通过
    Closed = 7, // 已关闭
}

const taskReviewStateMapping = {
    1: '#FF7D00',
    2: '#8F00FF',
    3: '#F53F3F',
    4: '#FF00C7',
    5: '#F53F3F',
    6: '#00B42A',
    7: '#4E5969',
};

interface ITaskItemType {
    id: string;
    key: string;
    cvatJobId: string;
    batchTaskId: number;
    cvatTaskId: string;
    subTaskStatusName: string;
    subTaskStatus: TaskItemReviewStateEnum;
    imageName: string;
    imageUrl: string;
    children?: ITaskItemType[];
    rejectReason?: string; // 驳回原因
}

function TaskDetailComponent(props): JSX.Element {
    const { task } = props;
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [selectRows, setSelectRows] = useState<ITaskItemType[]>([]);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);
    const [pageInfo, setPageInfo] = useState({ pageIndex: 1, pageSize: 20, total: 0 });
    const navigate = useNavigate();
    const pageSizeOptions = [10, 20, 50, 100];
    const [rejectVisible, setRejectVisible] = useState(false);
    const [rejectTitle, setRejectTitle] = useState('');
    const [currentRecord, setCurrentRecord] = useState<ITaskItemType>();
    const [handleJobStatus, setHandleJobStatus] = useState<JobStatusEnum>();

    function initModal(config: {
        type?: string;
        title: string;
        content: string | ReactNode;
        okText?: string;
        onOk?: Function;
        onCancel?: Function;
        cancelText?: string | ReactNode;
    }): void {
        const modal = config.type === 'confirm' ? Modal.confirm({}) : Modal.info({});
        modal.update({
            title: config.title,
            content: config.content,
            closable: false,
            okText: config.okText,
            onOk: () => {
                if (config.onOk) {
                    config.onOk();
                }
                modal.destroy();
            },
            onCancel: () => {
                if (config.onCancel) {
                    config.onCancel();
                }
                modal.destroy();
            },
            cancelText: config.cancelText || '取消',
        });
    }

    async function getSubTaskStateOption() {
        const res = await fetchSubTaskStatusTypes({});
        return res.statusList.map((v) => ({ label: v.statusName, value: v.status }));
    }

    async function changeSubTaskStatus(id: string, status: JobStatusEnum, remark?: string) {
        await auditTask({
            subTaskId: id,
            subTaskStatus: status, // JobStatusEnum.WAITING_SECOND_REVIEW
            remark,
        });
        tableRef.current?.reload();
    }

    async function handleRejectSubmit(values) {
        const { remark } = values;
        await changeSubTaskStatus(currentRecord?.id, handleJobStatus, remark);
        message.success(`${rejectTitle}成功！`);
    }

    async function submitFirstReview(record: ITaskItemType): Promise<void> {
        await changeSubTaskStatus(record.id, JobStatusEnum.WAITING_SECOND_REVIEW);
        message.success('提交初审成功！');
    }

    async function submitLastReview(record: ITaskItemType): Promise<void> {
        await changeSubTaskStatus(record.id, JobStatusEnum.SECOND_REVIEW_APPROVED);
        message.success('提交复审成功！');
    }

    function search(): void {
        formRef.current.submit();
        tableRef.current.reload();
    }
    function clear(): void {
        formRef.current?.resetFields();
        search();
    }

    async function batchSubmitFirstReview(): Promise<void> {
        await changeSubTaskStatus(selectRows.map((v) => v.id).join(','), JobStatusEnum.WAITING_SECOND_REVIEW);
        message.success('批量提交初审成功！');
    }

    async function closeSubTask(record: ITaskItemType): Promise<void> {
        await changeSubTaskStatus(record.id, JobStatusEnum.CLOSED);
        message.success('子任务关闭成功！');
    }

    async function goViewTaskPage(record: ITaskItemType, action: 'annotation' | 'view' | 'review' = 'view') {
        // 未创建cvat任务，创建任务
        if (!+record.cvatJobId) {
            const res = await createTask(record.id);
            record.cvatJobId = res.taskId;
            record.cvatJobId = res.jobId;
        }
        navigate(`/tasks/${record.cvatTaskId}/jobs/${record.cvatJobId}/subtask/${record.id}/action/${action}`);
    }

    const columns: ProColumns<ITaskItemType>[] = [
        {
            title: '子任务ID',
            dataIndex: 'id',
            sorter: true,
            key: 'dataId',
            valueType: 'text',
            search: true,
            order: 4,
            width: 220,
            render: (text, record) => (
                <span
                    className='cursor-pointer'
                    onClick={() => {
                        goViewTaskPage(record);
                    }}
                >
                    {text}
                </span>
            ),
        },
        {
            title: '数据名称',
            dataIndex: 'imageName',
            sorter: true,
            key: 'imageName',
            valueType: 'text',
            search: true,
            order: 3,
            width: 252,
            render: (text, record) => (
                <span
                    className='cursor-pointer'
                    onClick={() => {
                        goViewTaskPage(record);
                    }}
                >
                    {text}
                </span>
            ),
        },
        {
            title: '图片',
            dataIndex: 'imageUrl',
            sorter: false,
            search: false,
            valueType: 'image',
            key: 'imageUrl',
            render: (text, record) => <Image width={48} height={48} src={record.imageUrl} alt={record.imageName} />,
        },
        {
            title: '子任务状态',
            dataIndex: 'subTaskStatusName',
            key: 'subTaskStatusName',
            sorter: true,
            order: 6,
            search: true,
            valueType: 'select',
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择子任务状态',
            },
            request: async () => getSubTaskStateOption(),
            render: (text: ReactNode, record) => [
                <>
                    {
                        record.subTaskStatus === TaskItemReviewStateEnum.LastReviewReject ? (
                            <Tooltip title={`驳回原因：${record.rejectReason}`}>
                                <span
                                    className='flex flex-items-center'
                                    style={{ color: taskReviewStateMapping[record.subTaskStatus] }}
                                >
                                    <i
                                        style={{
                                            display: 'inline-block',
                                            marginRight: '6px',
                                            width: '4px',
                                            height: '4px',
                                            borderRadius: '2px',
                                            backgroundColor: taskReviewStateMapping[record.subTaskStatus],
                                        }}
                                    />
                                    {text}
                                    <AnnotationInfoIcon />
                                </span>
                            </Tooltip>
                        ) : ''
                    }
                    {
                        record.subTaskStatus === TaskItemReviewStateEnum.FirstReview ?
                            (
                                <span
                                    className='flex flex-items-center'
                                    style={{ color: taskReviewStateMapping[record.subTaskStatus] }}
                                >
                                    <i
                                        style={{
                                            display: 'inline-block',
                                            marginRight: '6px',
                                            width: '4px',
                                            height: '4px',
                                            borderRadius: '2px',
                                            backgroundColor: taskReviewStateMapping[record.subTaskStatus],
                                        }}
                                    />
                                    {text}
                                </span>
                            ) : ''
                    }
                </>
            ],
        },
        {
            title: '操作',
            dataIndex: 'handler',
            sorter: false,
            key: 'handler',
            valueType: 'option',
            search: false,
            fixed: 'right',
            render: (text, record) => [
                <ConfigProvider
                    theme={{
                        components: {
                            Button: {
                                paddingInline: 0,
                            },
                        },
                    }}
                >
                    {/* 待标注或者初审驳回的可以标注 */}
                    {record.subTaskStatus === TaskItemReviewStateEnum.Tagging ||
                        record.subTaskStatus === TaskItemReviewStateEnum.FirstReviewReject ? (
                        <>
                            <AuthPerm permission='tag'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        goViewTaskPage(record, 'annotation');
                                    }}
                                >
                                    标注
                                </Button>
                            </AuthPerm>
                            <AuthPerm permission='submitFirstReview'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        initModal({
                                            title: '提交初审',
                                            content: '请确认是否将子任务提交初审？',
                                            okText: '提交初审',
                                            onOk: () => {
                                                submitFirstReview(record);
                                            },
                                        });
                                    }}
                                >
                                    提交初审
                                </Button>
                            </AuthPerm>
                        </>
                    ) : (
                        ''
                    )}
                    {record.subTaskStatus === TaskItemReviewStateEnum.Tagging ? (
                        <AuthPerm permission='closetaskItem'>
                            <Button
                                type='link'
                                size='middle'
                                onClick={() => {
                                    closeSubTask(record);
                                }}
                            >
                                关闭任务
                            </Button>
                        </AuthPerm>
                    ) : (
                        ''
                    )}
                    {record.subTaskStatus === TaskItemReviewStateEnum.FirstReview ? (
                        <>
                            <AuthPerm permission='firstReview'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        goViewTaskPage(record, 'review');
                                    }}
                                >
                                    初审
                                </Button>
                            </AuthPerm>
                            <AuthPerm permission='rejectFirstReview'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        setRejectTitle('初审驳回');
                                        setHandleJobStatus(JobStatusEnum.FIRST_REVIEW_REJECTED);
                                        setCurrentRecord(record);
                                        setRejectVisible(true);
                                    }}
                                >
                                    初审驳回
                                </Button>
                            </AuthPerm>
                            <AuthPerm permission='submitLastReview'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        initModal({
                                            title: '提交复审',
                                            content: '请确认子任务是否初审通过，可提交复审？',
                                            okText: '提交复审',
                                            onOk: () => {
                                                submitLastReview(record);
                                            },
                                        });
                                    }}
                                >
                                    提交复审
                                </Button>
                            </AuthPerm>
                        </>
                    ) : (
                        ''
                    )}
                    {record.subTaskStatus === TaskItemReviewStateEnum.LastReview ? (
                        <>
                            <AuthPerm permission='lastReview'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        goViewTaskPage(record, 'review');
                                    }}
                                >
                                    复审
                                </Button>
                            </AuthPerm>
                            <AuthPerm permission='submitLastReview'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        setRejectTitle('复审驳回');
                                        setHandleJobStatus(JobStatusEnum.SECOND_REVIEW_REJECTED);
                                        setCurrentRecord(record);
                                        setRejectVisible(true);
                                    }}
                                >
                                    复审驳回
                                </Button>
                            </AuthPerm>
                            <AuthPerm permission='passAudit'>
                                <Button
                                    type='link'
                                    size='middle'
                                    onClick={() => {
                                        const res = fetchLastReviewValid(record.id, record.cvatJobId);
                                        if (res.valid) {
                                            initModal({
                                                title: '复审通过',
                                                content: '请确认子任务是否复审通过？',
                                                okText: '复审通过',
                                                onOk: () => {
                                                    submitLastReview(record);
                                                },
                                            });
                                        } else {
                                            initModal({
                                                type: 'confirm',
                                                title: '提示',
                                                content: '还有未完成复审的标签，请处理后再提交',
                                                okText: '我知道了',
                                                cancelText: <span />,
                                            });
                                        }
                                    }}
                                >
                                    复审通过
                                </Button>
                            </AuthPerm>
                        </>
                    ) : (
                        ''
                    )}
                    {record.subTaskStatus === TaskItemReviewStateEnum.PassLastReview ? '--' : ''}
                </ConfigProvider>,
            ],
        },
    ];

    return (
        <div>
            <div className='bg-#F7F8FA p-3 border-rd-4 m-4'>
                <Row className='m-b-12px'>
                    <Col span={8}>
                        <span className='color-#86909C'>任务批次ID：</span>
                        <span className='color-#1D2129'>{task.id}</span>
                    </Col>
                    <Col span={8}>
                        <span className='color-#86909C'>任务批次名称：</span>
                        <span className='color-#1D2129'>{task.batchTaskName}</span>
                    </Col>
                    <Col span={8}>
                        <span className='color-#86909C'>创建人：</span>
                        <span className='color-#1D2129'>{task.createUserName}</span>
                    </Col>
                </Row>
                <Row>
                    <Col span={8}>
                        <span className='color-#86909C'>创建时间：</span>
                        <span className='color-#1D2129'>{task.createTime}</span>
                    </Col>
                    <Col span={8}>
                        <span className='color-#86909C'>标注员：</span>
                        <span className='color-#1D2129'>{task.labeler}</span>
                    </Col>
                    <Col span={8}>
                        <Row>
                            <Col span={10}>
                                <span className='color-#86909C'>初审员：</span>
                                <span className='color-#1D2129'>{task.firstChecker}</span>
                            </Col>
                            <Col span={10} offset={1}>
                                <span className='color-#86909C'>复审员：</span>
                                <span className='color-#1D2129'>{task.rechecker}</span>
                            </Col>
                        </Row>
                    </Col>
                </Row>
            </div>
            <ProTable<ITaskItemType>
                actionRef={tableRef}
                formRef={formRef}
                columns={columns}
                style={{ padding: '0' }}
                expandable={{
                    expandRowByClick: true,
                    indentSize: 2,
                    expandedRowKeys,
                    onExpand: (expanded, record) => {
                        const expandedSet = new Set(expandedRowKeys);
                        if (expanded) {
                            expandedSet.add(record.key);
                        } else {
                            expandedSet.delete(record.key);
                        }
                        setExpandedRowKeys(Array.from(expandedSet));
                    },
                }}
                request={async (params, sort, filter) => {
                    const { id, subTaskStatusName = [], imageName } = params;
                    try {
                        let sortKey;
                        let sortType;
                        Object.keys(sort).forEach((v) => {
                            sortKey = v;
                            sortType = sort[v];
                        });
                        const sortAscColumn = sortType === 'ascend' ? sortKey : ''; // 升序字段
                        const sortDescColumn = sortType === 'descend' ? sortKey : '';
                        const r = await fetchSubTaskList({
                            pageIndex: params.current,
                            pageSize: params.pageSize,
                            id,
                            subTaskStatus: subTaskStatusName,
                            batchTaskId: task.id,
                            imageName,
                            sortAscColumn,
                            sortDescColumn,
                        });
                        const arr: ITaskItemType[] = [];
                        (r?.dataList).forEach((v) => {
                            const children: ITaskItemType[] = [];
                            if (v.subTaskImageList.length > 1) {
                                v.subTaskImageList.map((item, index) => {
                                    if (index) {
                                        children.push({
                                            ...v,
                                            ...item,
                                            key: `${v.id}${item.imageName}`,
                                        });
                                    }
                                });
                            }
                            if (children.length) {
                                arr.push({
                                    key: `${v.id}${v.subTaskImageList[0].imageName}`,
                                    ...v,
                                    imageName: v.subTaskImageList[0].imageName,
                                    imageUrl: v.subTaskImageList[0].imageUrl,
                                    children,
                                });
                            } else {
                                arr.push({
                                    key: `${v.id}${v.subTaskImageList[0].imageName}`,
                                    ...v,
                                    imageName: v.subTaskImageList[0].imageName,
                                    imageUrl: v.subTaskImageList[0].imageUrl,
                                });
                            }
                        });
                        return {
                            data: arr,
                            success: true,
                            total: r ? r.totalRow : 0,
                        };
                    } catch (error) {
                        return {
                            data: [],
                            success: true,
                            total: 0,
                        };
                    }
                }}
                scroll={{ y: 'calc(100vh - 420px)' }}
                pagination={{
                    pageSize: pageInfo.pageSize,
                    current: pageInfo.pageIndex,
                    total: pageInfo.total,
                    pageSizeOptions,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total}条`,
                    onChange: (page, pageSize) => {
                        setPageInfo({
                            ...pageInfo,
                            pageIndex: page,
                        });
                    },
                }}
                search={{
                    defaultCollapsed: false,
                    collapseRender: false,
                    searchText: '查询',
                    labelWidth: 'auto',
                    className: 'search-wrapper',
                    span: 12,
                    optionRender: () => [
                        <Button key='clear' onClick={() => clear()}>
                            重置
                        </Button>,
                        <Button key='search' type='primary' onClick={() => search()}>
                            查询
                        </Button>,
                    ],
                }}
                rowSelection={{
                    alwaysShowAlert: false,
                    onChange: (selectedKeys, selectedRowsArr) => {
                        setSelectRows(selectedRowsArr);
                    },
                }}
                tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
                    <Space size={24}>
                        <span>
                            已选
                            {selectRows.length}项
                            <Button type='link' style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                                取消选择
                            </Button>
                        </span>
                    </Space>
                )}
                options={{
                    density: false,
                    setting: false,
                    reload: false,
                }}
                tableAlertOptionRender={() => (
                    <Space size={16}>
                        <AuthPerm permission='batchSubmitFirstReview'>
                            <Tooltip title='勾选「待标注」子任务，可批量提交初审'>
                                <Button
                                    key='batchHandel'
                                    type='primary'
                                    disabled={
                                        !selectRows.length &&
                                        selectRows.every((v) => v.subTaskStatus === TaskItemReviewStateEnum.Tagging)
                                    }
                                    onClick={() => {
                                        initModal({
                                            title: '提交初审',
                                            content: `请确认是否将${selectRows.length}个子任务提交初审？`,
                                            okText: '提交初审',
                                            onOk: () => {
                                                batchSubmitFirstReview();
                                            },
                                            cancelText: '取消',
                                        });
                                    }}
                                >
                                    提交初审
                                </Button>
                            </Tooltip>
                        </AuthPerm>
                    </Space>
                )}
            />
            <RejectForm
                visible={rejectVisible}
                title={rejectTitle}
                onSubmit={handleRejectSubmit}
                close={() => {
                    setRejectVisible(false);
                    setCurrentRecord(null);
                }}
            />
        </div>
    );
}

export default TaskDetailComponent;
